/*
 * @Author: xuanjiu 
 * @Date: 2017-11-13 11:02:46 
 * @Last Modified by: zhangxuanjiu
 * @Last Modified time: 2018-04-24 15:12:45
 */
import AssetAdapter from './AssetAdapter.ts'

declare var global: any

class ResLoader extends egret.EventDispatcher {
  private hasStarted: boolean = false
  private groupName: string
  public constructor() {
    super()
  }

  public startLoading(groupName: string): void {
    if (this.hasStarted) {
      return
    }
    this.hasStarted = true
    this.groupName = groupName
    console.log('startLoading')
    //inject the custom material parser
    //注入自定义的素材解析器
    let assetAdapter = new AssetAdapter();
    egret.registerImplementation("eui.IAssetAdapter",assetAdapter)
    
    //初始化Resource资源加载库
    RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this)
  }

  /**
   * 配置文件加载完成,开始预加载皮肤主题资源和preload资源组。
   * Loading of configuration file is complete, start to pre-load the theme configuration file and the preload resource group
   */
  private onConfigComplete(event:RES.ResourceEvent):void {
    RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
    // load skin theme configuration file, you can manually modify the file. And replace the default skin.
    RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
    RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
    RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
    RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
    RES.loadGroup(this.groupName)
  }

  private onResourceLoadComplete(event:RES.ResourceEvent):void {
    this.dispatchEvent(new egret.Event(event.groupName + 'Complete'))
  }

  /**
   * 资源组加载出错
   * Resource group loading failed
   */
  private onResourceLoadError(event:RES.ResourceEvent):void {
    //TODO
    console.warn("Group:" + event.groupName + " has failed to load");
    //忽略加载失败的项目
    //ignore loading failed projects
    alert('网络请求出错')
    this.onResourceLoadComplete(event);
  }

  /**
   * preload资源组加载进度
   * loading process of preload resource
   */
  private onResourceProgress(event:RES.ResourceEvent):void {
    if (event.groupName == 'bgui') {
      this.dispatchEventWith('loadingBguiProgress', false, {
        itemsLoaded: event.itemsLoaded,
        itemsTotal: event.itemsTotal
      })
    }
  }

  /**
   * 资源组加载出错
   *  The resource group loading failed
   */
  private onItemLoadError(event:RES.ResourceEvent):void {
    alert("请求出错")
    console.warn("Url:" + event.resItem.url + " has failed to load")
  }
}

export default ResLoader